package br.com.educa.service;

import org.springframework.dao.DataAccessException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import br.com.educa.modelo.security.Usuario;


@Service
public class LoginService implements UserDetailsService {

	 @Override
	 @Transactional(readOnly=true)
	 public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
		 Usuario us = new Usuario();
		 try{
			 us = Usuario.findUsuariosByUsernameEquals(username).getSingleResult();
		 } catch (Exception e) {
	            e.printStackTrace();
	     }
		 return us;
	 }
	 
	 public static Usuario buscarUsuarioLogado(){
		 
		 SecurityContext securityContext = SecurityContextHolder.getContext();
		 Authentication auth = securityContext.getAuthentication();
		 Usuario user = (Usuario) auth.getPrincipal();
		return user;
		 
	 }
	 
   
}
